import hex_md5 from 'md5'
import jsrsasign from 'jsrsasign'

/**
 * @description 获取屏幕配置
 */
export function windowConfig() {
	let obj={
		win:uni.getWindowInfo(),
		//#ifdef MP
		mpButton:uni.getMenuButtonBoundingClientRect()
		//#endif
	}
    return obj
}


/**
 * @description url跳转
 */
export function GoUrl(url:string,act?:number) {
	if(typeof(act)!='undefined'){
		if(act===0){
			uni.reLaunch({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}		
		if(act===1){
			uni.redirectTo({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}
		if(act===2){
			uni.switchTab({
				url:url,
				fail: function(e){
					console.log("链接发生错误",e);
				}
			})				
		}
	}else{
		uni.navigateTo({
			url:url,
			fail: function(e){
				console.log("链接发生错误",e);
			}
		})		
	}
}



/**
 * @description 限制字符输出
 */
export function limtStrLen(val:string,num:number){
	if(val.length>num) return val.substring(0,num)+"..";
	return val;
}




/**
 * @description 屏幕短消息提示
 * @param  { string } messagestr 传入需要提示的字符串
 */
export function Toast(messagestr:string) {
	uni.showToast({
		icon:'none',
		title: messagestr,
		duration:1500 
	});
	setTimeout(()=>{uni.hideLoading()},1500);
}



/*隐藏部分电话号码*/
export function hiddenPhone(phonenum:string) {
	let str=phonenum.toString();
	return str.substring(0, 3) + '****' + str.substring(str.length - 4)
}



//去除左右两边空格
export function trim(s:string){
    return s.replace(/(^\s*)|(\s*$)/g,"");
}
	
	
	
//js对象数组模糊过滤模糊搜索
//let list=this.fuzzyQuery(this.list,'平次",'name');
export function fuzzyQuery(list:[],keyword:string,attribute:string) {
	const reg:RegExp = new RegExp(keyword) //创建正则表达式
	const arr:any = []
	for (let i = 0; i<list.length; i++) {
		if(reg.test(list[i][attribute])) {
			arr.push(list[i])
		}
	}
	return arr;
}


/**
 * @description 时间戳转日期 毫秒数"1531116791000"得到时间2018-07-09 14:13:11"
 * @param  { timestamp } key 时间戳
 */
export function timestampToDate(timestamp:number) {
	var d = new Date(timestamp); //得到普通的时间
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());  
	var second = change(d.getSeconds());
	function change(t:number) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	return time;
}

/**
 * @description 日期转换中文时间
 * @param  { dateStr } string 2022-08-07
 * @returns  2022年08月07日
 */
export function ChineseDate(dateStr:string) {
	if(dateStr.indexOf("-")!=-1){
		let year=dateStr.split("-")[0];
		let month=dateStr.split("-")[1];
		let day=dateStr.split("-")[2];
		return year+"年"+month+"月"+day+"日";
	}
	return dateStr;
}











	
/**
 * @description 缓存
 * @param  { string } key 键值
 * @param  { string } val 值
 * @param  { expireTime } expireTime 过期时间毫秒 1000 * 60 * 0.5
 */
export interface storeType{
	key:string,
	val:string,
	expireTime:number
}
export function storeSet(key:string,val:string,expireTime:number) {
	let obj:storeType = {
		key:key,
		val:val,
		expireTime: new Date().getTime() + expireTime   // 毫秒*秒*分钟
	};
	uni.setStorageSync(key,obj);
}
export function storeGet(key:string) {
	let obj:storeType
	if(uni.getStorageSync(key)!=null){
		obj=uni.getStorageSync(key);
		const time:number = new Date().getTime(); //获取当前时间
		if (time < obj.expireTime) {
			return obj.val;
		} else {
			uni.removeStorageSync(key);
		}
	}else{
		return null;
	}
}





/**
 * @description 登录
 */
export async function getPhoneNumber(e:any,loginCode:any,callBack:Function){
	
		console.log("是否同意获取手机号码:",e);
		uni.showLoading({
			title:"登录中"
		})
		if (e.detail.errMsg == "getPhoneNumber:ok") {
			setTimeout(()=>{ uni.hideLoading() },1000);
			//Toast("同意获取手机号码");
			//let iv:string=e.detail.iv;
			//let encryptedData:string=e.detail.encryptedData;
			//先登录获取用户session_key
			let loginRes:any=await wxUserLogin("/api/wxLogin",{logincode:loginCode.value});
			console.log("登录结果",loginRes)
			if(loginRes.data.code===200 && loginRes.data.data.token!=null && loginRes.data.data.token!=""){
				//Toast("登录成功");
				//设置token否则后续无法操作
				uni.setStorageSync("token",loginRes.data.data.token);	
				if(callBack instanceof Function) return callBack(loginRes); 
				//之后获取用户手机号
				// let paraData:wxDecryptPhone={
				// 	token:uni.getStorageSync("token"),
				// 	iv:iv,
				// 	encryptedData:encryptedData,	
				// }
				// //paraData.token=null;
				// //console.log("上传的参数",paraData)
				// let res:any=await getDecryptPhone("/wxDecryptPhone",paraData);
				// //console.log('服务器返回res: ',res);
				// //获取到手机成功后，表示登录成功，永久化保存数据
				// if(res.data.code===200){
				// 	if(callBack instanceof Function) return callBack(res); 
				// }else{
				// 	Toast(res.data.msg);
				// }
			}else{
				Toast(loginRes.data.msg);
			}
		}else{
			setTimeout(()=>{ uni.hideLoading() },5000);
		}
	
}


/*微信登录结果*/
const wxUserLogin=(url:string,paraData:string)=>{
	console.log("登录参数:",paraData);
	return new Promise((resolve, reject) => {
		uni.$tools.Reqeust(url,paraData,'POST').then((res:any)=>{
				console.log('微信登录结果:',res);
				resolve(res);
		})	
	});
}










/**
 * @description 生成订单 /api/generateOrder
 */
export function generateOrder(apiUrl:string,paraData:any){
	return new Promise((resolve, reject) => {
		console.log("订单参数:",paraData);
		uni.$tools.Reqeust(apiUrl,paraData,'POST').then((res:any)=>{
			console.log("生成订单结果:",res);
			resolve(res);
		})		
	});
}


/**
 * @description 订单支付 /api/orderPay
 */
export function payOrder(apiUrl:string,orderNo:String,productName:String,money:number){
	let paraPayData={
		productname:productName,
		orderno:orderNo,
		totalpay:money
	}
	uni.$tools.Reqeust(apiUrl,paraPayData,'POST').then((res:any)=>{
		console.log("生成订单结果:",res);
		if(res.data.code===200){
			uni.hideLoading();
			let orderinfo:any = {};
			orderinfo.appid = res.data.data.appid;
			orderinfo.description = res.data.data.description,
			orderinfo.out_trade_no = res.data.data.out_trade_no,
			orderinfo.prepayid = res.data.data.prepay_id;
			console.log("111111111111111111",orderinfo);
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: orderinfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
				timeStamp:res.data.data.timeStamp, //微信小程序必填
				nonceStr:res.data.data.nonceStr, //微信小程序必填
				package:"prepay_id="+res.data.data.prepay_id, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=xx。
				signType:"RSA", //RSA  v3支付默认且仅支持RSA
				paySign:paySignForRSA(res.data.data.appid,res.data.data.timeStamp,res.data.data.nonceStr,res.data.data.prepay_id),
				success: (sucres) => {
					console.log("调用requestPayment结果:", sucres);
					uni.hideLoading();
					
					if(productName==="Ai慢病管理"){
						//uni.navigateBackMiniProgram();
						uni.navigateBackMiniProgram({
						  extraData: {
						    'isPay': true
						  },
						  success(res) {
						    // 返回成功
						  }
						})
						return;
					}
					
					setTimeout(()=>{
						let keyid=uni.getStorageSync("keyid");
						if(keyid==='shop'){
							return uni.$tools.GoUrl("/pages/shop_ordersList/shop_ordersList");
						}					
						return uni.$tools.GoUrl("/pages/sjorders/sjorders",2);
					},1000);
				 },
				 fail: (err) => {
					 console.log('支付fail:' + JSON.stringify(err));
					 uni.hideLoading();
					 uni.$tools.Toast("支付失败");
				 }
			});	
		}
	})		
}


//MD5签名
// const paySign=(appId:string,timeStamp:string,nonceStr:string,prepayid:string)=>{
// 	let signStr="appId="+appId+"&nonceStr="+nonceStr+"&package=prepay_id="+prepayid+"&timeStamp="+timeStamp;
// 	console.log("待签名字符串:",signStr,hex_md5(signStr));
// 	return hex_md5(signStr);
// }

//RAS签名
const paySignForRSA=(appId:string,timeStamp:string,nonceStr:string,prepayid:string)=>{
	     let encipher = new jsrsasign.RSAKey()
	      // 私钥 在微信端申请好后会有，一般由后端提供
	      // 在商户号平台可以找到
	      const key = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDBznHpajnWKiHT
lF24PxP3MrZFi3bcLjf05P38UjJ0HRcRctIn5Nl0JK1x5JyZJjmknw+chODJXW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XwFqDhuc4iWb+UAS7+f/lQ3dE
LhMby85s5noBNJB5QDPwwz/spsWB9ANGEJOMaq3zVpHfnBcLADAOpMDjwQKBgDUZ
55VHvHMuhKaVxp4C1ZqSetOODlObpcbBaay8PU08Iq8KWHn1rKnBao0KzkjHjKrs
7ytL1tTyYgKOURTIkGFaLBN46/XDrKzM7SK3VPFTcvsTOm9iYZTv2bKk87b1Pxqc
UZbQSbxh+GrQmmvy+k9QdWPbIcAwzAkPeBxZX9EBAoGBAM5XCDDcNF9HWedBliBQ
yZ5Xl3r02FgHexX/8buHHSEJJjG6+hdj/WcyzV0cSO9aUdF3W13TCs1GcgPQ5UOE
jv/SsWlerDzGCXO20QFd8XYuocCqq0U/Pw8yYXpOWg/woHF4V8E7VVDLQiZR1ATC
6MjVz5HbPNwrAAy5dAt6JajW
-----END PRIVATE KEY-----`
	      // 把私钥转成16进制并设置秘钥
	      encipher = jsrsasign.KEYUTIL.getKey(key)
	      // 设置SHA256withRSA方式加密
	      const sig = new jsrsasign.KJUR.crypto.Signature({
	        alg: 'SHA256withRSA',
	      })
	      // 初始化
	      sig.init(encipher)
	      // 需要加密的字段，这里注意下一定要按每一个字段一行，切末位加上 \n
	      const str = `${appId}\n` + 
	      			  `${timeStamp}\n` + 
	      			  `${nonceStr}\n` + 
	      			  `prepay_id=${prepayid}\n`
	      const paySign = sig.updateString(str)
	      // 加密后,转成base64
	      return jsrsasign.hextob64(sig.sign())
}